/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { BaseCommand, IAssemblyConstraint } from '@amcax/base';
import { pickedProductData } from '@app-base/common/components/pick-input/types';
import { DocumentContext } from '@app-base/common/providers/documentProvider';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { PRODUCT_EVENT } from '@app-cad/common/Constants';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { ctx2, userEvents } from '@app-cad/module';
import { FeaturedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
import i18n from 'i18next';
import { useContext, useState } from 'react';
import { getAllConstraints } from '../../utils';
import './index.scss';

function ConstrainDialog({ title, onClose }: FeaturedCmdDialogParams) {
  const { docTree } = useContext(DocumentContext);
  const allconstraints = getAllConstraints(docTree);
  const checkDuplication = (item, target) => {
    if (!allconstraints) {
      return true;
    }
    return !allconstraints?.some((i) => {
      const obj = i?.originalObj as IAssemblyConstraint;
      return obj?.item === item && obj?.target === target && obj?.type === 7;
    });
  };
  const [selectData, setSelectData] = useState<pickedProductData>(null);
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      selectData: {
        type: 'string',
        title: '几何图形',
        format: PickInputRJSFFormat.PickProduct,
      },
    },
  };

  const checkAndFinish = async () => {
    const id = selectData?.idInfo?.o;

    if (!checkDuplication(id, id)) {
      MessageTip.error('创建失败，已有相同约束');
      return;
    }
    const params = {
      item: id,
      target: id,
      type: 7,
      // label: '固定',
      val: 0,
    };
    await ctx2.commandCenters.assemblyCommands
      .addConstraint(params)
      .catch((err) => {
        MessageTip.error(err.message);
      });
    userEvents.emit(PRODUCT_EVENT.UPDATE_CONSTRAINTS);

    onClose();
  };
  useCommand('cmd-constrain-fix', {
    onClose,
    finishDraw: checkAndFinish,
  });
  return (
    <PickableCommandForm
      title={title}
      schema={schema}
      validator={validator}
      onClose={onClose}
      onChange={(v) => {
        setSelectData(v.selectData);
      }}
      onSubmit={checkAndFinish}
      extraUiSchema={{
        selectData: {
          'ui:placeholder': '请输入几何图形',
          'ui:autofocus': true,
        },
      }}
    />
  );
}

export const cmdConstrainFix: BaseCommand = {
  id: 'CmdConstrainFix',
  label: 'command.constrain-fix',
  icon: 'constraints/fixed',
  create: (label: string, onClose: () => void, props) => (
    <ConstrainDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
